package com.qen.wrapper.segments;

import cn.hutool.core.util.StrUtil;
import com.qen.enums.SqlKeyword;
import com.qen.wrapper.ISqlSegment;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.joining;

/**
 * Order By SQL 片段
 *
 * @author licz
 * @since 1.0.0
 */
public class OrderBySegmentList extends AbstractISegmentList {

    @Override
    protected boolean transformList(List<ISqlSegment> list, ISqlSegment firstSegment, ISqlSegment lastSegment) {
        list.remove(0);
        final List<ISqlSegment> sqlSegmentList = new ArrayList<>(list);
        list.clear();
        list.add(() -> sqlSegmentList.stream().map(ISqlSegment::getSqlSegment).collect(joining(StrUtil.SPACE)));
        return true;
    }

    @Override
    protected String childrenSqlSegment() {
        if (isEmpty()) {
            return StrUtil.EMPTY;
        }
        return this.stream().map(ISqlSegment::getSqlSegment).collect(Collectors.joining(StrUtil.COMMA, StrUtil.SPACE + SqlKeyword.ORDER_BY.getSqlSegment() + StrUtil.SPACE, StrUtil.EMPTY));
    }
}
